<template>
    <!-- 内容总结 -->
    <div class="cont-summary-box flex flex-col flex justify-center my-4 w-full items-center">
        <div class="textera-save-style w-2/5">
            <el-input type="textarea" v-model="textareaVal" :rows="10" placeholder="请输入需要总结的文本"
                class="text-input no-border" @focus="handleFocus" @blur="handleBlur" ref="textrea"/>
            <el-icon class="clear-button" @click="clearInput" @mouseover="overColor" @mouseout="outColor">
                <Close />
            </el-icon>
            <div class="button-container">
                <el-button @click="setDefault">设为默认值</el-button>
                <el-button type="primary" @click="saveInput">开始提取</el-button>
            </div>
        </div>
        <div class="ai-answers w-2/5 " v-show="cardShow">
            <div class="flex flex-col">
                <div class="flex self-start p-2.5  max-box">
                    <div class="w-11 h-11 mr-2.5">
                        <img src="/src/assets/images/robot_circle.png" alt="" class="w-11 h-full rounded">
                    </div>
                    <div class="ai-answer p-2.5 m-1.5 relative rounded-lg">
                        <div class="ai-triangle absolute"></div>
                        <span v-if="!aiAnswer" class="flex items-center"><img src="../../assets/images/avatar/long.gif"
                                alt="" class="w-5 h-5 mr-1">AI正在总结......</span>
                        <span v-else> AI总结内容如下</span>
                        <div class="rounded-lg flex  justify-end items-center">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <el-card v-if="aiAnswer" style="width: 40%">{{ displayText }}</el-card>
    </div>
</template>
<script lang="ts" setup>

const textareaVal = ref('');
//控制ai默认显示内容
const aiAnswer = ref(false);
//控制card显示隐藏
const cardShow = ref(false);
// 流式输出是否完成   请求完成给false
const disabledvalue = ref(false);

const displayText = ref("");

const router = useRouter()

const textrea =ref()
const Token = <string>localStorage.getItem('accessToken');
const handleFocus = () => {
    document.querySelector('.textera-save-style').classList.add('change-color');
};

const handleBlur = () => {
    document.querySelector('.textera-save-style').classList.remove('change-color');
};
const overColor = () => {
    document.querySelector('.clear-button').classList.add('a');
}
const outColor = () => {
    document.querySelector('.clear-button').classList.remove('a');
}
//小叉叉清空事件
const clearInput = () => {
    textareaVal.value = '';
};
//开始提取事件
const saveInput = () => {
    // console.log('开始提取');
    // aiAnswer.value=true;
    // 让ai先展示出来
    if (!textareaVal.value.trim()) {
        ElMessage.error('请填写识别文本');
        return;
    }
    cardShow.value = true;
    aiAnswer.value = false;
    getsearchproblem()
};
function getsearchproblem() {
    disabledvalue.value = true;
    displayText.value = ""; // 清空之前的显示内容
    // 调用回复接口
    fetch(import.meta.env.VITE_APP_BASE_API + "/open/summary", {
        method: "POST",
        headers: {
            token: Token,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            content: textareaVal.value.replace(/\n/g, ""),
            stream: true,
        }),
    })
        .then((response) => {
            aiAnswer.value = true;
            const reader = response.body.getReader();
            return new ReadableStream({
                async start(controller) {
                    while (true) {
                        const { done, value } = await reader.read()
                        if (done) {
                            // 如果读取完成，关闭流
                            controller.close();
                            return;
                        }
                        displayText.value += new TextDecoder().decode(value);
                    }
                },
            });
        })
        .then((stream) => {
            return new Response(stream).text();
        })
        .then((result) => {
            disabledvalue.value = false;
        })
        .catch((error) => {
            console.error("Fetch error:", error);
        });

}
//设为默认值
const setDefault = () => {
    // console.log('设为默认值');
    const defaultStr = `  一个春暖花开的日子，我和同学们兴高采烈地去春游啦！经过一个多小时的车程，我们终于到达了目的地——辰山植物园。进园后，首先映入眼帘的是一片樱花林。一阵微风吹过，樱花的花瓣如同一只只白蝴蝶在空中翩翩起舞，随风飘来，又随风飘去，真是好看极了！同学们纷纷在樱花树下照相，留下这美好的一刻。离开了樱花林，穿过春景园，我们来到了儿童乐园。同学们有的直奔彩色小山的山顶，有的冲向小桥……我则在走木桩，一开始，木桩很低，我轻而易举地走完了。可是后来木桩越来越高了，我鼓足勇气，一步一步，稳稳地踩在了木桩上，终于，我成功地走完了所有木桩！在一旁的老师和同学们都为我喝彩。下一个景点是矿坑公园。还没走进公园，远远地就听见瀑布“哗哗”的流水声，这让我想起了“飞流直下三千尺，疑是银河落九天”这句诗。循着水声，我看到了一个大大的矿坑，水流从山顶一泻而下，激起了一阵阵水花，那景色真是壮观！走过竹林，我们又来到了温室，令我印象深刻的植物是“见血封喉”。当我走过“见血封喉”时，浑身都起了鸡皮疙瘩，因为在《美丽的西双版纳》这篇课文里，我知道“见血封喉”这种树的叶子是有毒的，今天目睹了它的庐山真面目，真让人心惊胆战！最后，我们在草坪上野餐，玩游戏，大家玩得不亦乐乎！这次辰山植物园之行让我们每一个小朋友都走进了大自然，感受到春的气息，我多么希望能留住春姑娘的脚步啊！`
    textareaVal.value = defaultStr;
};

watch(
    () => router.currentRoute.value,
    (newValue: any) => {
        textareaVal.value = '';
        cardShow.value = false;
        aiAnswer.value = false;
        if(textrea.value){
            textrea.value.focus();
        }
    },
    { immediate: true }
)
onMounted(()=>{
    textrea.value.focus();
})
</script>
<style scoped>
.cont-summary-box{
    margin: 0;
    padding-top: 30px;
}
:deep(.el-textarea__inner) {
    border: none;
    box-shadow: none;
    resize: none;
}

.textera-save-style.change-color {
    border-color: #409eff;
}

.textera-save-style {
    border-radius: 5px;
}

.clear-button.a {
    color: #409eff;
}

.center-list {
    width: 100%;
    height: 100%;
    flex: auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    overflow: scroll;
    scrollbar-width: none;
}

.max-box {
    max-width: 70%;
}

.ai-triangle {
    width: 0;
    height: 0;
    border-left: 10px solid rgba(0, 0, 0, 0);
    border-right: 10px solid rgba(0, 0, 0, 0);
    border-top: 10px solid var(--v-chat_box_shadow_1);
    top: 8px;
    left: -10px;
}

.ai-answer {
    background-color:var(--v-ai-custmer-bg-color,#434346);
    color: var(--v-txt_icon_black_2, #1a2029);
}
.ai-answers{
    margin: 20px 0;
}
.el-card{
    background-color: rgba(0, 0, 0, 0) !important;
}
</style>